package com.shfl.servermanage.logic.api;


import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageInfo;
import com.shfl.servermanage.common.ApiResultPagingHelper;
import com.shfl.servermanage.common.RequestHelper;
import com.shfl.servermanage.common.SystemConstant;
import com.shfl.servermanage.logic.bean.SysAttachment;
import com.shfl.servermanage.logic.constants.CommonConstants;
import com.shfl.servermanage.logic.model.response.SysReleaseLogPageResponse;
import com.shfl.servermanage.logic.service.SysAttachmentService;
import com.shfl.servermanage.logic.service.SysReleaseLogServer;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/release/log")
@Api(value = "构建日志", description = "构建日志")
public class ReleaseLogController {

    @Autowired
    private SysReleaseLogServer sysReleaseLogServer;

    @Autowired
    private SysAttachmentService sysAttachmentService;

    @GetMapping(value = "/page/list")
    public ApiResultPagingHelper<SysReleaseLogPageResponse, Void> page(
            RequestHelper requestHelper
    ) {
        requestHelper.apply();
        Map<String, Object> objectMap = requestHelper.getKeyMap();
        PageInfo<SysReleaseLogPageResponse> pageInfo = sysReleaseLogServer.findPage(requestHelper.getPageable(), objectMap);
        if (pageInfo.getTotal() > 0) {
            List<Long> relationIds = pageInfo.getList().stream().map(SysReleaseLogPageResponse::getId).collect(Collectors.toList());
            Map<String, Object> objectMap1 = new HashMap<>();
            objectMap1.put("relationIds", relationIds);
            objectMap1.put("attachType", CommonConstants.AttachType.SHELL_LOG.getValue());
            List<SysAttachment> sysAttachmentList = sysAttachmentService.findByMap(objectMap1);
            pageInfo.getList().forEach(item -> {
                List<SysAttachment> subSysAttachmentList = sysAttachmentList.stream().filter(
                        subItem -> Objects.equals(subItem.getRelationId(), item.getId())).collect(Collectors.toList());
                if (!CollectionUtil.isEmpty(subSysAttachmentList)) {
                    SysAttachment sysAttachment = subSysAttachmentList.get(0);
                    item.setPath(CommonConstants.FILE_ADDRESS_READ.concat(sysAttachment.getAttachUrl()));
                }
            });
        }
        return new ApiResultPagingHelper<>(SystemConstant.RE_SUCCESS_CODE,
                pageInfo.getTotal(), pageInfo.getPageSize(), pageInfo.getPageNum(),
                pageInfo.getList());
    }
}
